#include <func.h>
#define pipe1 "/tmp/pipe1"
#define pipe2 "/tmp/pipe2"

int p0;
int p1;
int p2;
int p3;
struct msgbuf
{
   long mtype;
   char mtext[4096];
};
void sigFunc(int num)
{
   kill(p0, 9);
   kill(p1, 9);
   kill(p2, 9);
   kill(p3, 9);
}
int main(int argc, char *argv[])
{
   // 创建一片共享内存；
   int shmid = shmget(1000, 4096, IPC_CREAT | 0666);
   ERROR_CHECK(shmid, -1, "shmget");
   int *pid = (int *)shmat(shmid, NULL, 0);
   ERROR_CHECK(pid, (void *)-1, "shmat");
   pid[2] = getpid();
   printf("pid=%d\n", pid[2]);
   // while (pid[0] == 0 || pid[1] == 0 || pid[2] == 0 || pid[3] == 0)
   // {
   // }

   p0 = pid[0];
   p1 = pid[1];
   p2 = pid[2];
   p3 = pid[3];
   signal(SIGUSR1, sigFunc);
   mkfifo(pipe1, 0600);
   mkfifo(pipe2, 0600);
   int fdw = open(pipe1, O_WRONLY);
   int fdr = open(pipe2, O_RDONLY);
   // int semid = semget(10001,1,IPC_CREAT|0600);
   // ERROR_CHECK(semid,-1,"semget");
   // semctl(semid,0,GETVAL);

   // struct sembuf p;
   // struct sembuf v;
   // p.sem_op = 1;
   // p.sem_flg = SEM_UNDO;
   // p.sem_num = semid;
   // v.sem_op = -1;
   // v.sem_flg = SEM_UNDO;
   // v.sem_num = semid;
   char buf[4096] = {0};
   // 创建消息队列
   int msgid = msgget(1000, IPC_CREAT | 0600);

   // 添加监听;
   while (1)
   {
      fd_set rdset;
      FD_ZERO(&rdset);
      FD_SET(fdr, &rdset);
      FD_SET(STDIN_FILENO, &rdset);
      struct timeval timeout;
      timeout.tv_sec = 5000;
      timeout.tv_usec = 500000;

      int ret = select(fdr + 1, &rdset, NULL, NULL, &timeout);
      if (ret == 0)
      {
         puts("timeout!");
         continue;
      }
      if (FD_ISSET(STDIN_FILENO, &rdset))
      {
         memset(buf, 0, sizeof(buf));
         int ret = read(STDIN_FILENO, buf, sizeof(buf));
         if (ret == 0)
         {
            puts("end\n");
            break;
         }
         write(fdw, buf, strlen(buf) - 1);
         // 消息队列
         struct msgbuf mbuf;
         mbuf.mtype = 1;
         strcpy(mbuf.mtext, buf);
         msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
      }
      if (FD_ISSET(fdr, &rdset))
      {

         memset(buf, 0, sizeof(buf));
         int ret = read(fdr, buf, sizeof(buf));
         if (ret == 0)
         {
            puts("你是个好人\n");
            break;
         }
         printf("buf=%s\n", buf);
      }
   }

   return 0;
}